import {BaseService} from 'egg-cool-service';
// import * as _ from 'lodash';

/**
 * 商品-分类
 */
export default class GoodsProductService extends BaseService {
    /**
     * 分页查询
     * @param query
     */
    async page (query) {
        // sex = 0
        const {status , cateIds = '' , banner = 0 , recommend = 0 , video = 0 , brandIds = "" , keyword = ""} = query;
        //
        // d.name AS cateName

        // const exists = await this.getRepo().sys.User.findOne({ id: query.username });
        // if (!_.isEmpty(exists)) {
        //     throw new Error('用户名已经存在~');
        // }

        // console.log(cateIds)
        const sql = `
        SELECT
            a.id,a.name,a.createTime,a.updateTime,a.status,a.cateId,a.bannerImage,a.sex,a.tags,a.files,a.banner,a.summary,a.recommend,a.viewCount,a.keyword,
            a.video,
            b.name AS cateName,
            c.name AS brandName
        FROM
            goods_product a
            LEFT JOIN goods_cate b on a.cateId = b.id
            LEFT JOIN goods_brand c on a.brandId = c.id
        WHERE 1 = 1
            ${ this.setSql (status , 'and a.status = ?' , [status]) }
            ${ this.setSql (cateIds , 'and a.cateId in (?)' , [cateIds.split (',')]) }
            ${ this.setSql (brandIds , 'and a.brandId in (?)' , [brandIds.split (',')]) }
            ${ this.setSql (keyword && keyword.indexOf ('男') > - 1 && keyword.indexOf ('男女') == - 1 && keyword.indexOf ('中性') == - 1 , 'and a.sex in (?) ' , [[this.app.config.sex.man]]) }
            ${ this.setSql (keyword && keyword.indexOf ('女') > - 1 && keyword.indexOf ('男女') == - 1 && keyword.indexOf ('中性') == - 1 , 'and a.sex in (?) ' , [[this.app.config.sex.woman]]) }
            ${ this.setSql (keyword && (keyword.indexOf ('男女') > - 1 || keyword.indexOf ('中性') > - 1) , 'and a.sex in (?) ' , [[this.app.config.sex.both]]) }
            ${ this.setSql (keyword.replace ('男' , '').replace ('女' , '')
                        .replace ('男女' , '').replace ('中性' , '') ,
                'and ( a.name like ? or a.keyword like ?  or a.summary like ? ) ' , [`%${ keyword }%` , `%${ keyword }%` , `%${ keyword }%`]) }
            ${ this.setSql (banner == 1 , `and a.banner = ?` , [banner]) }
            ${ this.setSql (recommend == 1 , `and a.recommend = ?` , [recommend]) }
            ${ video == 1 ? 'and a.video is not null' : '' }
        GROUP BY a.id
        `;
        // ${ this.setSql(sex>0, 'and a.sex = ?', [sex]) }
        // ${ this.setSql(keyword.indexOf('男女')>-1, 'and a.sex = ?', [this.app.config.sex.both]) }
        // if(banner == 1){
        //     console.log(sql)
        // }
        // ${ this.setSql(video == 1,`and a.video is not null`,[video])}
        const result = await this.sqlRenderPage (sql , query);
        if ( result.list ) {
            result.list.map (item => {
                // console.log(this.app.config.charSPLIT)
                // console.log(item.tags)

                // item.files = item.files?item.files.split(this.app.config.charSPLIT).map(data=>{
                //     const [url,width,height,name,size,mimeType,hash] = data.split(this.app.config.charComma)
                //     let option = {
                //         url:url+'-qianyouzhuo',width,height,name,size,mimeType,hash
                //     }
                //     return option
                // }):[]
                // item.bannerImage = item.bannerImage?item.bannerImage.split(this.app.config.charSPLIT).map(data=>{
                //     const [url,width,height,name,size,mimeType,hash] = data.split(this.app.config.charComma)
                //     let option = {
                //         url:url+'-logo',width,height,name,size,mimeType,hash
                //     }
                //     return option
                // })[0]:{}
                item.tags = item.tags ? item.tags.split (this.app.config.charSPLIT).filter (item => item != '' && item != null) : [];
                // item.tags = item.tags?JSON.parse(item.tags):[]

                // let files = item.files?JSON.parse(item.files):[]
                // item.files = files.map(data=>{
                //     data.url = data.url + '-qianyouzhuo'
                //     return data
                // })
                delete item.files;
                delete item.video;
                delete item.updateTime;

                // item.video = item.video?JSON.parse(item.video):{url:''}

                item.bannerImage = item.bannerImage ? JSON.parse (item.bannerImage) : {url : ''};
                if ( item.bannerImage.url && (banner == 0 || !banner) ) {
                    item.bannerImage.url = item.bannerImage.url + this.app.config.pictureSplit.logo;
                } else if ( item.bannerImage.url && banner == 1 ) {
                    item.bannerImage.url = item.bannerImage.url + this.app.config.pictureSplit.banner;
                }

                return item;
            });
        }
        return result;
    }

    /**
     * banner查询
     * @param query
     */
    async medias (query) {
        const status = 1;
        // d.name AS cateName

        const sql = `
        SELECT
            a.id,a.bannerImage
        FROM
            goods_product a
        WHERE 1 = 1
            ${ this.setSql (status , 'and a.status = ?' , [status]) }
        `;
        // ORDER BY
        // a.createTime ASC

        const result = await this.sqlRenderPage (sql , query);
        if ( result.list ) {
            result.list.map (item => {
                item.bannerImage = item.bannerImage ? JSON.parse (item.bannerImage) : {url : ''};
                if ( item.bannerImage.url ) {
                    item.bannerImage.url = item.bannerImage.url + this.app.config.pictureSplit.logo;
                }
                return item;
            });
        }
        return result;
    }

    /**
     * 根据ID获得商品信息
     * @param id
     * @param entity
     */
    public async info (id , entity) {
        let item = await entity.findOne ({id});
        item.viewCount = item.viewCount ? Number (item.viewCount) + 1 : 0;
        await this.getRepo ().goods.Product.save (item);
        item.tags = item.tags ? item.tags.split (this.app.config.charSPLIT).filter (item => item != '' && item != null) : [];

        let files = item.files ? JSON.parse (item.files) : [];
        item.files = files.map (data => {
            data.url = data.url + this.app.config.pictureSplit.detail;
            return data;
        });

        item.video = item.video ? JSON.parse (item.video) : {};

        item.bannerImage = item.bannerImage ? JSON.parse (item.bannerImage) : {};
        if ( item.bannerImage.url ) {
            item.bannerImage.url = item.bannerImage.url + this.app.config.pictureSplit.logo;
        }

        item.like = 0;
        // console.log(info)
        if ( this.ctx.wx_decoded && this.ctx.wx_decoded.openid ) {
            const {openid} = this.ctx.wx_decoded;
            const likeInfo = await this.getRepo ().goods.Like.findOne ({openid , productId : id});
            if ( likeInfo ) {
                item.like = 1;
            }
        }
        return item;
    }

    //下架
    async undercarriage (params) {
        const {id} = params;
        const info = await this.getRepo ().goods.Product.findOne ({id});
        info.status = 0;
        await this.getRepo ().goods.Product.save (info);
    }

    //上架
    async grounding (params) {
        const {id} = params;
        const info = await this.getRepo ().goods.Product.findOne ({id});
        info.status = 1;
        await this.getRepo ().goods.Product.save (info);
    }

    /**
     * 移动分类
     * @param params
     */
    public async move (params) {
        const {cateId , productIds} = params;
        await this.nativeQuery ('update goods_product a set a.cateId = ? where a.id in (?)' , [cateId , productIds]);
    }

    async add (param) {
        await this.getRepo ().goods.Product.save (param);
    }

}
